#-*- encoding: utf8 -*-

__author__ = u'<havard@gulldahl.no> Håvard Gulldahl'
__license__ = 'GPL v2'

import sys
from PyQt4 import QtGui, QtCore

LOGFILE = 'gcontacts.log'

class ContactsWidget(QtGui.QTreeWidget):
  vcard_mimetypes = ['text/directory; charset="utf-8"; profile="vCard"', 'text/x-vcard']
  moz_mimetypes = ['text/x-moz-address', ]
  file_suffixes = ['.contact', '.vcf']
  dragStartPos = QtCore.QPoint()

  def dragEnterEvent(self, event):
    if __debug__: print "dragenter"
    if event.source() == self:
      event.ignore()
      return
    mime = event.mimeData()
    for t in self.vcard_mimetypes+self.moz_mimetypes: # look for vcard or mozcard
      if mime.hasFormat(t):
        event.acceptProposedAction()
        if __debug__: print "accepted"
        return
    if mime.hasUrls(): # look at the source url
      for url in [ unicode(u.toString()) for u in mime.urls()]:
        for s in self.file_suffixes:
          if s in url: 
            event.acceptProposedAction()
            if __debug__: print "accepted"
            return
    if __debug__: 
      print "ignored"
      print mime.hasUrls(),  [ unicode(u.toString()) for u in mime.urls()]
      print [ unicode(u.toLocalFile()) for u in mime.urls()]
      from pprint import pprint
      lf = file(LOGFILE,  'w')
      pprint([ (str(s), str(event.mimeData().data(s)))  for s in event.mimeData().formats() ],  lf)
      lf.close()
    event.ignore()
      
  def dragMoveEvent(self, event):
    if __debug__: print "dragmove"
    mime = event.mimeData()
    for t in self.vcard_mimetypes+self.moz_mimetypes:
      if mime.hasFormat(t):
        event.acceptProposedAction()
        return
    if mime.hasUrls(): # look at the source url
      for url in [ unicode(u.toString()) for u in mime.urls()]:
        for s in self.file_suffixes:
          if s in url: 
            event.acceptProposedAction()
            return
    event.ignore()
      
  def dropEvent(self, event):
    if __debug__: print "drop"
    mime = event.mimeData()
    handled = False
    for t in self.vcard_mimetypes: # look at mime type
      if __debug__: print "looking at ", t
      if mime.hasFormat(t):
        vcardData = mime.data(t)
        event.setDropAction(QtCore.Qt.CopyAction)
        event.accept()
        self.emit(QtCore.SIGNAL('droppedVCard(PyQt_PyObject)'), unicode(vcardData, 'utf-8'))
        #self.new(unicode(vcardData, 'utf-8'))
        handled = True
    if handled: return
    for t in self.moz_mimetypes: # look at mime type
      if __debug__: print "looking at ", t
      if mime.hasFormat(t):
        textaddress = unicode(mime.data(t),  'utf-16').replace('\x00',  '')
        event.setDropAction(QtCore.Qt.CopyAction)
        event.accept()
        self.emit(QtCore.SIGNAL('droppedAddress(PyQt_PyObject)'), textaddress)
        #self.new(unicode(vcardData, 'utf-8'))
        handled = True
    if handled: return
    if mime.hasUrls(): # look at the source url
      for url in mime.urls(): 
        for s in self.file_suffixes:
          if s in unicode(url.toString()): 
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            #break
            self.emit(QtCore.SIGNAL('droppedUrl(PyQt_PyObject)'), url)
            handled = True
    if handled: return
    if mime.hasText(): # look for "name <address@example.com>" and "address@example.com (name)"
      textaddress = unicode(mime.text(),  'utf-8')
      if '@' in textaddress: # TODO: proper testing of email address
        event.setDropAction(QtCore.Qt.CopyAction)
        event.accept()
        self.emit(QtCore.SIGNAL('droppedAddress(PyQt_PyObject)'), textaddress)
        handled = True
    if not handled: 
      event.ignore()

  def mimeData(self, indexes):
    if __debug__: print "mimeData", indexes
    mime = QtGui.QTreeWidget.mimeData(self, indexes)
    vcard = emails = ''
    for item in indexes:
      vcard += item.contact.ToVCard() + '\r\n'
      try: _e = item.text(1).split(',')[0] # HACK: get first email
      except IndexError: _e = ''
      emails += '%s <%s>' % (item.text(0), _e) + ', '
    for mt in self.vcard_mimetypes:
      mime.setData(mt, vcard)
    mime.setText(emails)
    return mime

  def mimeTypes(self):
    if __debug__: print "mimeTypes"
    return self.vcard_mimetypes

